package cn.codewen.shop.dao.impl;

import cn.codewen.shop.dao.AdminDao;
import cn.codewen.shop.pojo.Admin;
import cn.codewen.shop.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class AdminDaoImpl implements AdminDao {
    //0. 定义conn和stm
    private Connection conn;
    private Statement stm;

    //1. 构造方法
    public AdminDaoImpl() {
        try {
            //1.1. 得到连接
            conn = JDBCUtils.getConnection();
            //1.2. 创建stm对象
            stm = conn.createStatement();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public Admin getOneByUsername(String username) {
        //0. 声明一个admin对象
        Admin admin = null;
        try {
            //1. 定义SQL语句
            String sql = "select * from admin where username='" + username + "'";
            System.out.println(sql);
            //2. 执行SQL语句
            ResultSet rs = stm.executeQuery(sql);
            //3. 遍历rs
            if (rs.next()) {
                admin = new Admin();
                admin.setUsername(rs.getString("username"));
                admin.setPassword(rs.getString("password"));
            }
            //4. 关闭对象
            //JDBCUtils.close(rs, stm, conn);
            rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //5. 返回数据
        return admin;
    }
}
